import { createStore } from 'vuex'

export default createStore({
  state: {
    timerMinutes: 25,
    breakMinutes: 5,
    longBreakMinutes: 15,
    sessionsBeforeLongBreak: 4,
    currentSession: 0,
    isTimerRunning: false,
    timeLeft: 25 * 60,
    timerType: 'work', // 'work', 'break', 'longBreak'
    tasks: [],
    completedSessions: [],
    isLoggedIn: false
  },
  mutations: {
    startTimer(state) {
      state.isTimerRunning = true
    },
    pauseTimer(state) {
      state.isTimerRunning = false
    },
    resetTimer(state) {
      if (state.timerType === 'work') {
        state.timeLeft = state.timerMinutes * 60
      } else if (state.timerType === 'break') {
        state.timeLeft = state.breakMinutes * 60
      } else {
        state.timeLeft = state.longBreakMinutes * 60
      }
      state.isTimerRunning = false
    },
    setTimeLeft(state, time) {
      state.timeLeft = time
    },
    setTimerType(state, type) {
      state.timerType = type
    },
    incrementSession(state) {
      state.currentSession = (state.currentSession + 1) % state.sessionsBeforeLongBreak
    },
    addTask(state, task) {
      state.tasks.push(task)
    },
    updateTask(state, { id, completed }) {
      const task = state.tasks.find(t => t.id === id)
      if (task) {
        task.completed = completed
      }
    },
    deleteTask(state, id) {
      state.tasks = state.tasks.filter(t => t.id !== id)
    },
    addCompletedSession(state, session) {
      state.completedSessions.push(session)
    },
    updateSettings(state, settings) {
      state.timerMinutes = settings.timerMinutes || state.timerMinutes
      state.breakMinutes = settings.breakMinutes || state.breakMinutes
      state.longBreakMinutes = settings.longBreakMinutes || state.longBreakMinutes
      state.sessionsBeforeLongBreak = settings.sessionsBeforeLongBreak || state.sessionsBeforeLongBreak
      state.resetTimer()
    },
    setLoggedIn(state, value) {
      state.isLoggedIn = value
    }
  },
  actions: {
    startTimer({ commit, state, dispatch }) {
      commit('startTimer')
      
      const interval = setInterval(() => {
        if (state.timeLeft <= 0) {
          clearInterval(interval)
          dispatch('completeSession')
        } else {
          commit('setTimeLeft', state.timeLeft - 1)
        }
      }, 1000)
      
      // 存储计时器引用以便暂停
      this._timerInterval = interval
    },
    pauseTimer({ commit }) {
      commit('pauseTimer')
      clearInterval(this._timerInterval)
    },
    resetTimer({ commit }) {
      commit('resetTimer')
      clearInterval(this._timerInterval)
    },
    completeSession({ commit, state, dispatch }) {
      // 添加完成的会话到历史记录
      commit('addCompletedSession', {
        id: Date.now(),
        type: state.timerType,
        date: new Date(),
        minutes: state.timerType === 'work' ? state.timerMinutes : 
                 state.timerType === 'break' ? state.breakMinutes : state.longBreakMinutes
      })
      
      // 检查是否需要开始长休息
      if (state.timerType === 'work') {
        commit('incrementSession')
        if (state.currentSession === 0) {
          commit('setTimerType', 'longBreak')
        } else {
          commit('setTimerType', 'break')
        }
      } else {
        commit('setTimerType', 'work')
      }
      
      // 重置计时器
      dispatch('resetTimer')
      
      // 自动开始下一个计时器
      dispatch('startTimer')
      
      // 播放完成提示音
      const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3')
      audio.play()
    },
    addTask({ commit }, task) {
      commit('addTask', {
        id: Date.now(),
        title: task.title,
        completed: false
      })
    },
    updateTask({ commit }, { id, completed }) {
      commit('updateTask', { id, completed })
    },
    deleteTask({ commit }, id) {
      commit('deleteTask', id)
    },
    updateSettings({ commit }, settings) {
      commit('updateSettings', settings)
    }
  },
  getters: {
    formattedTime: (state) => {
      const minutes = Math.floor(state.timeLeft / 60)
      const seconds = state.timeLeft % 60
      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    },
    progressPercentage: (state) => {
      let totalSeconds
      if (state.timerType === 'work') {
        totalSeconds = state.timerMinutes * 60
      } else if (state.timerType === 'break') {
        totalSeconds = state.breakMinutes * 60
      } else {
        totalSeconds = state.longBreakMinutes * 60
      }
      return (1 - state.timeLeft / totalSeconds) * 100
    },
    todaySessions: (state) => {
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      
      return state.completedSessions.filter(session => {
        const sessionDate = new Date(session.date)
        sessionDate.setHours(0, 0, 0, 0)
        return sessionDate.getTime() === today.getTime()
      })
    },
    totalFocusTimeToday: (state, getters) => {
      return getters.todaySessions
        .filter(session => session.type === 'work')
        .reduce((total, session) => total + session.minutes, 0)
    }
  }
})